module(..., package.seeall)

require "log"
require "http"
require "mqtt"
require "config"
require "misc"
require "aLiOutMsg"
require "aLiInMsg"
require "httpsGet"
require "aLiOTA"

local ready = false

function isReady() return ready end

local function startALiMqtt()
    sys.taskInit(function()
        local retryConnectCnt = 0
        local errorCnt = 0

        sys.wait(6000)
        --
        if socket.isReady() == false then
            retryConnectCnt = 0
            sys.waitUntil("IP_READY_IND", 300000)
        end

        while true do
            if socket.isReady() == false then
                retryConnectCnt = 0
                sys.waitUntil("IP_READY_IND", 300000)
            end

            if socket.isReady() == true and
                (nvm.get("ALI_DEVICE_SECRET") == "" or
                    nvm.get("ALI_DEVICE_IOTID") == "") then
                httpsGet.http_register()
                sys.waitUntil("ALI_REGISTER", 30000)
            end

            if socket.isReady() == true and nvm.get("ALI_DEVICE_SECRET") ~= "" and
                nvm.get("ALI_DEVICE_IOTID") ~= "" then
                local imei = misc.getImei()
                local client_id = "GWRD_" .. imei ..
                                      "|securemode=3,signmethod=hmacsha1,timestamp=2524608000000|"
                local client_user = "GWRD_" .. imei .. "&" ..
                                        config.ALI_PRODUCTKEY
                local content = "clientId" .. "GWRD_" .. imei .. "deviceName" ..
                                    "GWRD_" .. imei .. "productKey" ..
                                    config.ALI_PRODUCTKEY ..
                                    "timestamp2524608000000"
                local client_password = crypto.hmac_sha1(content, content:len(),
                                                         nvm.get(
                                                             "ALI_DEVICE_SECRET"),
                                                         nvm.get(
                                                             "ALI_DEVICE_SECRET"):len())

                local regist_topic = "/sys/" .. config.ALI_PRODUCTKEY .. "/" ..
                                         "GWRD_" .. imei ..
                                         "/thing/sub/register_reply"
                local topo_topic = "/sys/" .. config.ALI_PRODUCTKEY .. "/" ..
                                       "GWRD_" .. imei .. "/thing/topo/add_reply"
                local login_topic = "/ext/session/" .. config.ALI_PRODUCTKEY ..
                                        "/" .. "GWRD_" .. imei ..
                                        "/combine/login_reply"
                local post_topic = "/sys/" .. config.ALI_PRODUCTKEY .. "/" ..
                                       "GWRD_" .. misc.getImei() ..
                                       "/thing/event/property/history/post_reply"
                local service_topic = "/sys/" .. config.ALI_PRODUCTKEY .. "/" ..
                                          "GWRD_" .. misc.getImei() ..
                                          "/thing/service/{tsl.functionBlockId}:{tsl.service.identifier}_reply"
                local ota_topic = "/ota/device/upgrade/" ..
                                      config.ALI_PRODUCTKEY .. "/" .. "GWRD_" ..
                                      misc.getImei()
                local topo_change = "/sys/" .. config.ALI_PRODUCTKEY .. "/" ..
                                        "GWRD_" .. misc.getImei() ..
                                        "/thing/topo/change"
                local rrpc_topic = "/sys/" .. config.ALI_PRODUCTKEY .. "/" ..
                                       "GWRD_" .. misc.getImei() ..
                                       "/rrpc/request/+"

                local mqttClient
                mqttClient = mqtt.client(client_id, 120, client_user,
                                         client_password)
                log.info("MQTT_INFO", imei, client_id, client_user,
                         client_password)

                if mqttClient:connect(config.ALI_INSTANCEID ..
                                          ".mqtt.iothub.aliyuncs.com", 1883,
                                      "tcp") then
                    retryConnectCnt = 0
                    errorCnt = 0
                    ready = true
                    sys.publish("ALI_MQTT_READY", true)
                    log.info("MQTT", "ALI_MQTT_READY")

                    aLiOTA.versionUpload() -- 向阿里云推送当前的版本号

                    mqttClient:subscribe(regist_topic)
                    mqttClient:subscribe(topo_topic)
                    mqttClient:subscribe(login_topic)
                    mqttClient:subscribe(post_topic)
                    mqttClient:subscribe(service_topic)
                    mqttClient:subscribe(ota_topic)
                    mqttClient:subscribe(topo_change)
                    mqttClient:subscribe(rrpc_topic)

                    while true do
                        if not aLiInMsg.proc(mqttClient) then
                            break
                        end
                        if not aLiOutMsg.proc(mqttClient) then
                            break
                        end
                    end

                    aLiOutMsg.unInit()
                    ready = false
                    errDump.appendErr("Ali connect LOST|" .. tool.miscTime() ..
                                          ",")
                else
                    retryConnectCnt = retryConnectCnt + 1
                    errorCnt = errorCnt + 1
                end

                if retryConnectCnt >= 5 then
                    -- link.shut()
                    retryConnectCnt = 0
                end
                sys.wait(5000)
            else
                -- httpsGet.http_register()
                -- sys.waitUntil("ALI_REGISTER", 30000)
                log.info("ALI LOSE CONNECT")
                -- net.switchFly(true)
                -- sys.wait(20000)
                -- net.switchFly(false)
            end

            if errorCnt > 1000 then
                sys.restart("ALI_NET_ERROR_REBOOT|" .. tool.miscTime())
            end

        end
    end)
end

sys.taskInit(function() startALiMqtt() end)

